import socket
import struct


def check_sum(packet):
    sum = 0
    count_to = (len(packet)//2)*2
    count = 0
    while count < count_to:
        sum += ((packet[count+1] << 8) | packet[count])
        count += 2

    if count_to < len(packet):
        sum += packet[len(packet)-1]
        sum = sum & 0xffffffff
    sum = (sum >> 16) + (sum & 0xffff)
    sum = sum + (sum >> 16)
    answer = ~sum
    answer = answer & 0xffff
    answer = answer >> 8 | (answer << 8 & 0xff00)
    return answer


def ping(ip):
    raw_socket = socket.socket(
        socket.AF_INET, socket.SOCK_RAW, socket.getprotobyname('icmp'))
    # packet为IP数据报
    packet = struct.pack('!BBHHH13s', 8, 0, 0, 1, 0, b'hello_python')
    packet_check_sum = check_sum(packet)
    packet = struct.pack('!BBHHH13s', 8, 0, packet_check_sum, 1, 0, b'hello_python')
    raw_socket.sendto(packet, (ip, 0))



ping('220.181.57.216')
